/* vuex状态管理 */
import { createStore } from "vuex";
import mutations from "./mutations";
import storage from "../utils/storage";
import { menuPermissionList } from "@/api/index.ts";
import utils from "@/utils/utils";
import router from "@/router/index";

const state = {
  userInfo: storage.getItem("userInfo") || "",
  menuList: storage.getItem("menuList") || [],
  actionList: storage.getItem("actionList") || [],
};
export default createStore({
  state,
  mutations,
  actions: {
    async loadAsyncRoutes() {
      let userInfo = storage.getItem("userInfo") || {};
      if (userInfo.token) {
        try {
          const { menuList } = await menuPermissionList();
          let routes = utils.generateRoute(menuList);
          console.log("routes", router.getRoutes(), routes);
          const modules = import.meta.glob("../views/*/index.vue");
          routes.map((route) => {
            // vite这里有坑，不能使用@
            let url = `../views/${route.component}/index.vue`;
            // 这里直接import 在webpack中可以，在vite中会出现警告
            // route.component = () => import(url);
            route.component = modules[url];
            router.addRoute("home", route);
          });
        } catch (err) {
          console.error(err);
        }
      }
    },
  },
});
